package com.hyh.user.filter;

import com.hyh.user.dao.MenuMapper;
import com.hyh.user.dao.UserMapper;
import com.hyh.user.domain.LoginUser;
import com.hyh.user.domain.User;
import com.hyh.user.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class AuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()){
            // 放行请求
            filterChain.doFilter(request, response);
            return;    // 结束方法
        }
        System.out.println(token);
        Long userId = null;
        Map<String,String> map = new HashMap<>();
        // 验证令牌
        try{
            userId = Long.valueOf(JwtUtil.verify(token).getClaim("id").asString());
            System.out.println(userId);
        }catch (Exception e) {
            e.printStackTrace();
            map.put("msg","无效签名！");
            map.put("state","false");
            String json = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return;
        }
        User user = userMapper.selectById(userId);
        if(Objects.isNull(user)){
            throw  new RuntimeException("用户不存在");
        }
        LoginUser loginUser = new LoginUser(user,menuMapper.selectAuthentication(userId));
        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser.getUser(),
                null,
                loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
